<?php
error_reporting(0);

define('IN_MUDDER', true);
define('DS',            DIRECTORY_SEPARATOR);
define('MUDDER_ROOT', substr(dirname(__FILE__), 0, -3));
define('MUDDER_CORE',   MUDDER_ROOT.'core'.DS);

$_G = array();
require MUDDER_ROOT.'./data/config.php';
$_G['cfg'] = include MUDDER_ROOT.'./data/cachefiles/modoer_config.php';

$text = trim($_GET['t']);
//文字解密
if(!isset($_GET['nc']) || !$_GET['nc']) {
	require MUDDER_ROOT.'core/helper/passport.php';
	$text = passport_decrypt($text, $_G['cfg']['authkey']);
}

if($_G['charset'] != 'utf-8') {
	require MUDDER_ROOT.'core/lib/chinese.php';
	$CHS = new ms_chinese($_G['charset'], 'utf-8');
	$text = $CHS->Convert($text);
}

//$width = (int)$_GET['w'];
$bg_color = isset($_GET['bgcolor'])?special_chars($_GET['bgcolor']):'#fff';
$font_size	= is_numeric(isset($_GET['size']))?$_GET['size']:10;
$font_color = isset($_GET['color'])?special_chars($_GET['color']):'#888';

//$width < 0 && $width = 0;
$font_size < 8 && $font_size = 12;

$fontfiles = MUDDER_ROOT.'static/images/fonts/simsun.ttc';
$fontinfo = imagettfbbox($font_size, 0, $fontfiles, $text);

$src_width = abs($fontinfo[0]) + $fontinfo[4] + 4;
$src_height = abs($fontinfo[1]) + abs($fontinfo[7]) + 4;

//图片尺寸
$width = $src_width;
$height = $src_height;

$image = imagecreatetruecolor($width, $height);	//创建图形

$bg_color = hex2rgb($bg_color);
$bg_color = imagecolorallocate($image, $bg_color['r'],$bg_color['g'],$bg_color['b']);	//背景色为白色

$font_color = hex2rgb($font_color);
$font_color = imagecolorallocate($image, $font_color['r'],$font_color['g'],$font_color['b']);    //定义灰色字体颜色

//填充背景
imagefilledrectangle($image, 0, 0, $width, $height, $bg_color);

$x = 0;
$y = $height - 4;
//写入字符串$text
imagettftext($image, $font_size, 0, $x, $y, $font_color, $fontfiles, $text);

//输出图片
header("Content-type: image/jpeg");
imagejpeg ($image);
//释放内存句柄
imagedestroy($image);

function hex2rgb($hexColor) {
	$color = str_replace('#', '', $hexColor);
	if (strlen($color) > 3) {
		$rgb = array(
			'r' => hexdec(substr($color, 0, 2)),
			'g' => hexdec(substr($color, 2, 2)),
			'b' => hexdec(substr($color, 4, 2))
		);
	} else {
		$color = str_replace('#', '', $hexColor);
		$r = substr($color, 0, 1) . substr($color, 0, 1);
		$g = substr($color, 1, 1) . substr($color, 1, 1);
		$b = substr($color, 2, 1) . substr($color, 2, 1);
		$rgb = array(
			'r' => hexdec($r),
			'g' => hexdec($g),
			'b' => hexdec($b)
		);
	}
	return $rgb;
}

//编码HTML，过滤换行回车，制表符，用于纯文本录入
function special_chars($string, $filter_id = FILTER_FLAG_STRIP_LOW) {
    if(is_array($string)) {
        foreach($string as $key => $val) $string[$key] = _T($val);
        return $string;
    } else {
        return trim(filter_var($string, FILTER_SANITIZE_SPECIAL_CHARS, $filter_id));
    }
}